<script setup lang="ts">
import { getHomeBanner, getHomeCategory, getHomeHot } from '@/services/home'
import CustomNavbar from './components/CustomNavbar.vue'
import CategoryPanel from './components/CategoryPanel.vue'
import HotPanel from './components/HotPanel.vue'
import PageSkeleton from './components/PageSkeleton.vue'
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
import type { BannerItem, CategoryItem, HotItem } from '@/types/home'
import type { XtxGuessInstance } from '@/types/component'
const isLoading = ref(false)
// 页面加载时执行数据获取操作
onLoad(async () => {
  isLoading.value = true
  await Promise.all([getHomeBannerData(), getHomeCategoryData(), getHomeHotData()])
  isLoading.value = false
})

// 轮播图数据
const bannerList = ref<BannerItem[]>([])
/**
 * 获取轮播图数据
 *
 * @returns 无返回值
 */
const getHomeBannerData = async () => {
  const res = await getHomeBanner()
  if (res.code == '1') bannerList.value = res.result
}
// 分类面板数据
const categoryList = ref<CategoryItem[]>([])
/**
 * 获取首页分类面板数据
 *
 * @returns Promise<any> 分类面板数据
 */
const getHomeCategoryData = async () => {
  // 分类面板数据
  const res = await getHomeCategory()
  categoryList.value = res.result
}
// 热门榜单数据
const hotList = ref<HotItem[]>([])

/**
 * 获取首页热门榜单数据
 *
 * @returns 无返回值
 */
const getHomeHotData = async () => {
  // 热门榜单数据
  const res = await getHomeHot()
  hotList.value = res.result
}

// 猜你喜欢组件引用
const guessRef = ref<XtxGuessInstance>()
/**
 * 当页面滚动到底部时触发的事件处理函数
 *
 * @returns 无返回值
 */
const onScrolltolower = () => {
  guessRef.value?.loadMore()
}
const isTriggered = ref(false)
/**
 * 刷新下拉刷新事件
 *
 * 当用户进行下拉刷新操作时，会触发该函数，执行以下操作：
 * 1. 获取轮播图数据
 * 2. 获取首页分类数据
 * 3. 获取首页热门数据
 */
const onRefresherrefresh = async () => {
  isTriggered.value = true // 标记为已触发，防止多次下拉刷新
  // 重置猜你喜欢数据
  guessRef.value?.resetData()
  await Promise.all([
    getHomeBannerData(),
    getHomeCategoryData(),
    getHomeHotData(),
    guessRef.value?.loadMore(),
  ])
  isTriggered.value = false // 刷新完成后重置标记，以便下次下拉时再次触发
}
</script>

<template>
  <!-- 自定义导航栏 -->
  <CustomNavbar />
  <scroll-view
    class="scroll-view"
    scroll-y
    @scrolltolower="onScrolltolower"
    refresher-enabled
    :refresher-triggered="isTriggered"
    @refresherrefresh="onRefresherrefresh"
  >
    <PageSkeleton v-if="isLoading" />
    <template v-else>
      <!-- 轮播图 -->
      <XtxSwiper :list="bannerList" />
      <!-- 分类面板 -->
      <CategoryPanel :list="categoryList" />
      <!-- 热门榜单 -->
      <HotPanel :list="hotList" />
      <!-- 猜你喜欢 -->
      <XtxGuess ref="guessRef" />
    </template>
  </scroll-view>
</template>

<style lang="scss">
page {
  background-color: #f7f7f7;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.scroll-view {
  flex: 1;
}
</style>
